package com.data_structure_algorithm.data_structure.tree.bin_tree;
/**
 * @Authror PABLO
 * @Date 2022/3/29 22:30
 * @Desc 数组转化为二叉树
 */
public class ArrToBinaryTree {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};

        //测试
        ArrayBinaryTree a = new ArrayBinaryTree(arr);
        System.out.println("前序");
        a.preOrder();
        System.out.println();
        System.out.println("中序");
        a.midOrder();
        System.out.println();
        System.out.println("后序");
        a.postOrder();

    }
}
/**
 * @Authror PABLO
 * @Date 2022/3/29 22:30
 * @Desc 数组转化为二叉树
 */
//实现数组到二叉树的转化并且遍历
class ArrayBinaryTree {
    //存储二叉树节点的数组
    private int[] arr;

    public ArrayBinaryTree(int[] arr) {
        this.arr = arr;
    }
    public void preOrder(){
        this.preOrder(0);//这里入参为0是因为数组下标从0开始，0代表树的根节点
    }
    public void midOrder(){
        this.midOrder(0);
    }
    public void postOrder(){
        this.postOrder(0);
    }

    //完成顺序存储到二叉树的前序遍历
    //n为数组下标，默认从0开始
    public void preOrder(int n) {
        if (arr.length == 0 || arr == null) System.out.println("数组为空，不能前序遍历");
        //输出当前节点
        System.out.print(arr[n]+" ");
        //左递归遍历
        if ((2 * n + 1) < arr.length) preOrder(2 * n + 1);
        //右
        if ((2 * n + 2) < arr.length) preOrder(2 * n + 2);
    }
    //中序
    public void midOrder(int n ){
        if (arr.length == 0 || arr == null) System.out.println("数组为空，不能中序遍历");
        //左递归遍历
        if ((2 * n + 1) < arr.length) preOrder(2 * n + 1);
        System.out.print(arr[n]+" ");
        if ((2 * n + 2) < arr.length) preOrder(2 * n + 2);
    }
    //中序
    public void postOrder(int n ){
        if (arr.length == 0 || arr == null) System.out.println("数组为空，不能后序遍历");
        if ((2 * n + 2) < arr.length) preOrder(2 * n + 2);
        if ((2 * n + 1) < arr.length) preOrder(2 * n + 1);
        System.out.print(arr[n]+" ");

    }
}
